package com.example.demo.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import com.example.demo.HttpUtil;

import java.util.AbstractMap.SimpleEntry;
import java.util.LinkedList;

import it.unisa.dia.gas.jpbc.Element;
import net.sf.json.JSONObject;

public class Bob {
	private PubParams p;
	ProxyReEncrypt  d=new ProxyReEncrypt ();
	int t;	
	byte[] c1;
	Element c21;
	 SimpleEntry<List<Element>,List<Element>> xsAndYs;
	 
	 Element id,sk1,sk2;
	 byte[] encryptedMessage;
	public Bob(PubParams p,int t,Element id,Element sk1,Element sk2) {
		this.p=p;
		this.t=t;		
		
		this.id=id;
		this.sk1=sk1;
		this.sk2=sk2;
	}
	public void getRekey() throws UnsupportedEncodingException {
		List<Element> xs=new LinkedList(),ys=new LinkedList();
		for(int i=0;i<t;i++) {
			String index=new Integer(i).toString();
			String response="";
			try {
				response = HttpUtil.sendGet("http://localhost:8083/content/"+index, "UTF-8");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			JSONObject j=JSONObject.fromObject(response);
			String s=(String) j.get("c1");
			this.c1=((String) j.get("c1")).getBytes("ISO-8859-1");
			this.c21=p.G1.newElementFromBytes(((String) j.get("c21")).getBytes("ISO-8859-1"));
			Element x=p.Zr.newElementFromBytes(((String) j.get("x")).getBytes("ISO-8859-1"));
			Element y=p.G1.newElementFromBytes(((String) j.get("c31")).getBytes("ISO-8859-1"));
			xs.add(x);
			ys.add(y);
		}
		this.xsAndYs=new SimpleEntry<List<Element>,List<Element>>(xs,ys);
		
	}
	public void getEncryptedMessage(){
		String path="D:\\java_work\\data\\";
		try {
			this.encryptedMessage=d.readFile(path+"encryptedMessage");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public String dec(Element A) {
		
		byte[] m2=d.Dec2(p,t,c1,c21,xsAndYs,new SimpleEntry<>(sk1,sk2),A);
	   System.out.println("DEC2-message:"+new BigInteger(m2).toString());
	   try {
		  String  message=new String(AES.decrypt(encryptedMessage, new BigInteger(m2).toByteArray()));
		   return message;
		} catch (Exception e) {
			e.printStackTrace();
		}
	   return "";
	}
	
	public Element getA() {
		try {
			String s=HttpUtil.sendGet("http://localhost:8082/A","UTF-8");
			byte[] A=s.getBytes("ISO-8859-1");
			return p.Zr.newElementFromBytes(A);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		
		
	}
	

}
